package cn.doitedu;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.BytesWritable;
import org.roaringbitmap.longlong.Roaring64Bitmap;

import java.io.IOException;
import java.util.Date;

/**
 * @Author: 深似海
 * @Site: <a href="www.51doit.com">多易教育</a>
 * @QQ: 657270652
 * @Date: 2024/4/26
 * @Desc: 学大数据，上多易教育
 * 求bitmap中指定日期范围内的最大连续活跃天数
 **/
public class BitmapGetRangeMaxContinuousActiveDays extends UDF {

    private static final Date INITIAL = DateUtil.parse("2000-01-01");

    public int evaluate(BytesWritable bitmapBytesWritable, String startDate, int days) throws IOException {

        // 反序列化出bitmap对象
        Roaring64Bitmap bitmap = BitmapUtils.de(bitmapBytesWritable.getBytes());

        // 把范围起始日期换算成差值
        long start = DateUtil.between(INITIAL, DateUtil.parse(startDate), DateUnit.DAY);


        int max = 0;
        int tmp = 0;

        for (long i = start; i <= start + days; i++) {
            if (bitmap.contains(i)) {
                tmp++;
            } else {
                if (tmp > max) {
                    max = tmp;
                }
                tmp = 0;
            }
        }

        return max > tmp ? max : tmp;

    }


}
